package hero.mps.web.sys_login.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import hero.mps.config.jwt.JwtUtils;
import hero.mps.utils.ResultUtils;
import hero.mps.utils.ResultVo;
import hero.mps.web.school_class.service.SchoolClassService;
import hero.mps.web.school_major.service.SchoolMajorService;
import hero.mps.web.school_student.entity.SchoolStudent;
import hero.mps.web.school_student.service.SchoolStudentService;
import hero.mps.web.school_teacher.entity.SchoolTeacher;
import hero.mps.web.school_teacher.service.SchoolTeacherService;
import hero.mps.web.sys_login.entity.*;
import hero.mps.web.sys_menu.entity.RouterVO;
import hero.mps.web.sys_menu.entity.SysMenu;
import hero.mps.web.sys_menu.service.SysMenuService;
import hero.mps.web.sys_menu.utils.MakeTree;
import hero.mps.web.system_user.entity.SysUser;
import hero.mps.web.system_user.service.SysUserService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/login")
@RequiredArgsConstructor
public class LoginController {
    private final SysUserService sysUserService;
    private final SchoolStudentService schoolStudentService;
    private final SchoolTeacherService schoolTeacherService;
    private final JwtUtils jwtUtils;
    private final SysMenuService sysMenuService;
    private final SchoolClassService schoolClassService;
    private final SchoolMajorService schoolMajorService;

    /**
     * 首页总数统计
     * @return
     */
    @GetMapping("/getHomeCount")
    public ResultVo getHomeCount() {
        CountVO countVO = new CountVO();
        int stuCount = schoolStudentService.count();
        int teacherCount = schoolTeacherService.count();
        int classCount = schoolClassService.count();
        int majorCount = schoolMajorService.count();
        countVO.setStuCount(stuCount);
        countVO.setTeacherCount(teacherCount);
        countVO.setClassCount(classCount);
        countVO.setMajorCount(majorCount);
        return ResultUtils.success("获取成功", countVO);

    }
    /**
     * 修改密码
     * @param param
     * @return
     */
    @PostMapping("/updatePassword")
    public ResultVo updatePassword(@RequestBody UpdatePasswordParam param) {
        String old = DigestUtils.md5DigestAsHex(param.getOldPassword().getBytes());
        if (param.getUserType().equals("1")){
            SysUser user = sysUserService.getById(param.getUserId());
            if (!user.getPassword().equals(old)){
                return ResultUtils.error("旧密码错误");
            }
            user.setPassword(DigestUtils.md5DigestAsHex(param.getNewPassword().getBytes()));
            sysUserService.updateById(user);
            return ResultUtils.success("密码修改成功");
        }else if (param.getUserType().equals("2")){
            SchoolStudent schoolStudent = schoolStudentService.getById(param.getUserId());
            if (!schoolStudent.getPassword().equals(old)){
                return ResultUtils.error("旧密码错误");
            }
            schoolStudent.setPassword(DigestUtils.md5DigestAsHex(param.getNewPassword().getBytes()));
            schoolStudentService.updateById(schoolStudent);
            return ResultUtils.success("密码修改成功");
        }else if (param.getUserType().equals("3")){
            SchoolTeacher schoolTeacher = schoolTeacherService.getById(param.getUserId());
            if (!schoolTeacher.getPassword().equals(old)){
                return ResultUtils.error("旧密码错误");
            }
            schoolTeacher.setPassword(DigestUtils.md5DigestAsHex(param.getNewPassword().getBytes()));
            schoolTeacherService.updateById(schoolTeacher);
            return ResultUtils.success("密码修改成功");
        }else {
            return ResultUtils.error("密码修改失败,请联系管理员");
        }
    }

    @GetMapping("/getMenuList")
    public ResultVo getMenuList(LoginResult param) {
        if (param.getUserType().equals("1")) {
            // 根据用户id查询用户信息
            SysUser sysUser = sysUserService.getById(param.getUserId());
            // 菜单数据获取
            List<SysMenu> menuByUserId = null;
            if (StringUtils.isNotEmpty(String.valueOf(sysUser.getIsAdmin())) && sysUser.getIsAdmin().equals(1)){
                menuByUserId = sysMenuService.list();
            }else {
                menuByUserId = sysMenuService.getMenuByUserId(sysUser.getUserId());
            }
            // 过滤
            List<SysMenu> collect = menuByUserId.stream()
                    .filter(item -> item != null && !item.getType().equals(2))
                    .collect(Collectors.toList());
//            转为数组
            if(collect.size() == 0){
                return ResultUtils.error("暂未未分配菜单权限，请联系管理员");
            }
            // 组装理由数据格式
            List<RouterVO> routerVOS = MakeTree.makeRoute(collect, 0);
            return ResultUtils.success("查询成功", routerVOS);
        }else if (param.getUserType().equals("2")) {
            List<SysMenu> menuByUserId = sysMenuService.getMenuByStuId(Integer.parseInt(param.getUserId()));
            // 过滤
            List<SysMenu> collect = menuByUserId.stream()
                    .filter(item -> item != null && !item.getType().equals(2))
                    .collect(Collectors.toList());
//            转为数组
            if(collect.size() == 0){
                return ResultUtils.error("暂未未分配菜单权限，请联系管理员");
            }
            // 组装理由数据格式
            List<RouterVO> routerVOS = MakeTree.makeRoute(collect, 0);
            return ResultUtils.success("查询成功", routerVOS);
        }else if (param.getUserType().equals("3")) {
            List<SysMenu> menuByUserId = sysMenuService.getMenuByTeacherId(Integer.parseInt(param.getUserId()));
            // 过滤
            List<SysMenu> collect = menuByUserId.stream()
                    .filter(item -> item != null && !item.getType().equals(2))
                    .collect(Collectors.toList());
//            转为数组
            if(collect.size() == 0){
                return ResultUtils.error("暂未未分配菜单权限，请联系管理员");
            }
            // 组装理由数据格式
            List<RouterVO> routerVOS = MakeTree.makeRoute(collect, 0);
            return ResultUtils.success("查询成功", routerVOS);
        }else {
            return ResultUtils.error("用户类型错误");
        }

    }
    /**
     * 获取用户信息
     * @param loginParam
     * @return
     */
    @GetMapping("/getInfo")
    public ResultVo getUserInfo(LoginResult loginParam) {
        UserInfo userInfo = new UserInfo();
        if (loginParam.getUserType().equals("1")){
            SysUser sysUser = sysUserService.getById(loginParam.getUserId());
            userInfo.setName(sysUser.getUsername());
            userInfo.setIntroduction(sysUser.getNickName());
            userInfo.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
//            菜单数据获取
            List<SysMenu> menuByUserId;
            if (StringUtils.isNotEmpty(String.valueOf(sysUser.getIsAdmin())) && sysUser.getIsAdmin().equals(1)){
                menuByUserId = sysMenuService.list();
            }else {
                menuByUserId = sysMenuService.getMenuByUserId(sysUser.getUserId());
            }
//            过滤权限
            List<String> collect = menuByUserId.stream()
                    .filter(item -> item != null && StringUtils.isNotEmpty(item.getCode()))
                    .map(item -> item.getCode())
                    .collect(Collectors.toList());
//            转为数组
            if(collect.size() == 0){
                return ResultUtils.error("未分配权限");
            }
            String[] array = collect.toArray(new String[collect.size()]);
            userInfo.setRoles(array);
            return ResultUtils.success("查询成功", userInfo);
        } else if (loginParam.getUserType().equals("2")){
            SchoolStudent schoolStudent = schoolStudentService.getById(loginParam.getUserId());
            userInfo.setName(schoolStudent.getStuName());
            userInfo.setIntroduction(schoolStudent.getStuName());
            userInfo.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
//            获取学生权限
            List<SysMenu> menuByStuId = sysMenuService.getMenuByStuId(schoolStudent.getStuId());
//            过滤权限
            List<String> collect = menuByStuId.stream()
                    .filter(item -> item != null && StringUtils.isNotEmpty(item.getCode()))
                    .map(item -> item.getCode())
                    .collect(Collectors.toList());
//            转为数组
            if(collect.size() == 0){
                return ResultUtils.error("未分配权限");
            }
            String[] array = collect.toArray(new String[collect.size()]);
            userInfo.setRoles(array);
            return ResultUtils.success("查询成功", userInfo);
        }else if (loginParam.getUserType().equals("3")){
            SchoolTeacher schoolTeacher = schoolTeacherService.getById(loginParam.getUserId());
            userInfo.setName(schoolTeacher.getTeacherName());
            userInfo.setIntroduction(schoolTeacher.getTeacherName());
            userInfo.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
//            获取老师权限
            List<SysMenu> menuByTeacherId = sysMenuService.getMenuByTeacherId(schoolTeacher.getTeacherId());
//            过滤权限
            List<String> collect = menuByTeacherId.stream()
                    .filter(item -> item != null && StringUtils.isNotEmpty(item.getCode()))
                    .map(item -> item.getCode())
                    .collect(Collectors.toList());
//            转为数组
            if(collect.size() == 0){
                return ResultUtils.error("未分配权限");
            }
            String[] array = collect.toArray(new String[collect.size()]);
            userInfo.setRoles(array);
            return ResultUtils.success("查询成功", userInfo);
        }else {
            return ResultUtils.error("用户类型错误");
        }
    }

    /**
     * 登录
     */
    @PostMapping()
    public ResultVo login(@RequestBody LoginParam loginParam) {
        if (StringUtils.isEmpty(loginParam.getUsername())
                || StringUtils.isEmpty(loginParam.getPassword())
                || StringUtils.isEmpty(loginParam.getUserType())) {
            return ResultUtils.error("用户名，密码或用户类型不能为空");
        }
        if(loginParam.getUserType().equals("1")){
            String password = DigestUtils.md5DigestAsHex(loginParam.getPassword().getBytes());
            // 判断用户是否存在
            QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(SysUser::getUsername, loginParam.getUsername()).eq(SysUser::getPassword, password);
            SysUser sysUser = sysUserService.getOne(queryWrapper);
            if (sysUser == null) {
                return ResultUtils.error("用户名，密码错误");
            }
            // 获取token
            HashMap<String, String> map = new HashMap<>();
            map.put("username", sysUser.getUsername());
            map.put("userId", Long.toString(sysUser.getUserId()));
            String token = jwtUtils.generateToken(map);
            // 定义返回值
            LoginResult loginResult = new LoginResult();
            loginResult.setUsername(sysUser.getUsername());
            loginResult.setUserId(Long.toString(sysUser.getUserId()));
            loginResult.setUserType(loginParam.getUserType());
            loginResult.setToken(token);
            return ResultUtils.success("登录成功", loginResult);

        }else if (loginParam.getUserType().equals("2")){
            String password = DigestUtils.md5DigestAsHex(loginParam.getPassword().getBytes());
            LambdaQueryWrapper<SchoolStudent> queryWrapper = Wrappers.lambdaQuery(SchoolStudent.class)
                    .eq(SchoolStudent::getStuNum, loginParam.getUsername())
                    .eq(SchoolStudent::getPassword,password);
            SchoolStudent schoolStudent = schoolStudentService.getOne(queryWrapper);
            if (schoolStudent == null) {
                return ResultUtils.error("用户名，密码错误");
            }
            // 获取token
            HashMap<String, String> map = new HashMap<>();
            map.put("username", schoolStudent.getStuNum());
            map.put("userId", Long.toString(schoolStudent.getStuId()));
            String token = jwtUtils.generateToken(map);
            // 定义返回值
            LoginResult loginResult = new LoginResult();
            loginResult.setUsername(schoolStudent.getStuNum());
            loginResult.setUserId(Long.toString(schoolStudent.getStuId()));
            loginResult.setToken(token);
            loginResult.setUserType(loginParam.getUserType());
            return ResultUtils.success("登录成功", loginResult);

        }else if (loginParam.getUserType().equals("3")){
            String password = DigestUtils.md5DigestAsHex(loginParam.getPassword().getBytes());
            LambdaQueryWrapper<SchoolTeacher> queryWrapper = Wrappers.lambdaQuery(SchoolTeacher.class)
                    .eq(SchoolTeacher::getTeacherNum, loginParam.getUsername())
                    .eq(SchoolTeacher::getPassword, password);
            SchoolTeacher schoolTeacher = schoolTeacherService.getOne(queryWrapper);
            if (schoolTeacher == null) {
                return ResultUtils.error("用户名，密码错误");
            }
            // 获取token
            HashMap<String, String> map = new HashMap<>();
            map.put("username", schoolTeacher.getTeacherNum());
            map.put("userId", Long.toString(schoolTeacher.getTeacherId()));
            String token = jwtUtils.generateToken(map);
            // 定义返回值
            LoginResult loginResult = new LoginResult();
            loginResult.setUsername(schoolTeacher.getTeacherName());
            loginResult.setUserId(Long.toString(schoolTeacher.getTeacherId()));
            loginResult.setToken(token);
            loginResult.setUserType(loginParam.getUserType());
            return ResultUtils.success("登录成功", loginResult);
        }else {
            return ResultUtils.error("用户类型错误");
        }
    }
}
